/* eslint-disable */
import { jumpInclude , getQueryString,sendSbList } from './tool.js'
import { insertMoment } from '../../lib/utils.js';
import { isReprotCwbb, handelCwbb1, handleStep11, isReport, handelYHS } from './cwbbReport.js';
import {handleSmallIndex,handleSmallStep1,handleSmallStep2,handleSmallStep3} from './smallZeroReport.js';
import { incomeReport } from './incomeTaxReport.js';

function nextTick(findObj,tick){
  function doIt(){
    var obj=findObj()
    if(!obj){
      setTimeout(()=>{
        nextTick(findObj);
      },200);
    }
  }
  if(tick){
    setTimeout(doIt,tick);
  }else{
    doIt();
  }
}

let currentZeroInfo;

const pages={
  "index":"/portal/index.do",
  "step1":"/portal/include_sb.do?app_bh=030121010",
  "smallStep1":"/portal/include_sb.do?app_bh=030121011",
  "step3":"/portal/include_sb.do?app_bh=030121310",
  "step11": '/shenbao/index.action',
  "incomeStep":"/portal/include_sb.do?app_bh=030121210",
  "yhs": '/portal/include_sb.do?app_bh=030121311'
}

const isPage=(name)=>{
  return window.location.href.includes(pages[name])
}

const startZeroReport = async (data) => {
  let urls = [
    'https://etax.jiangsu.chinatax.gov.cn/sso/login',
  ];
  if (urls.includes(window.location.href)) {
    handleLogin(data.data.currentZeroInfo);
  }
  currentZeroInfo=data.data.currentZeroInfo;
};

const handleLogin=(info)=>{
  window.sessionStorage.setItem('isZero',true);
  window.localStorage.setItem('zeroStep',1);
  window.localStorage.removeItem("zzsReady");
  window.localStorage.removeItem("incomeReady");
  window.localStorage.removeItem("incomeInit");
  if(info.zzsType==="小规模纳税人"){
    window.sessionStorage.setItem('isSmall',true);
  }
  $(".xubox_close1").click();
  nextTick(()=>{
    $(".go_login").click();
    nextTick(()=>{
      let username=$("#username"),password=$("#password");
      if(username.length && password.length){
        username.focus();
        username.val(info.nationalTaxNo);
        username.blur();
        password.focus();
        password.val(info.nationalTaxPass);
        password.blur();
        return true
      }
    });
    return true;
  },200);
}

const handleIndex=()=>{
  nextTick(()=>{
    let lis = $('#sxtable tbody tr');
    if(lis.length > 1) {
      let isSmall=window.sessionStorage.getItem("isSmall");
        if(isSmall!="true"){
          if($("#sxtable tr:eq(1) .table_btn").length){
            if($("#sxtable tr:eq(1) td:eq(0)").html()=="增值税" && $("#sxtable tr:eq(1) .table_btn").html()=="申报"){
              $("#sxtable tr:eq(1) .table_btn").click();
            }else if($("#sxtable tr:eq(1) .table_btn").html()=="查看"){
              sendSbList(currentZeroInfo);
            }
          }
        }else{
          handleSmallIndex(currentZeroInfo);
        }
      return true;
    }
  })
}

const saveTable2=(win)=>{
  nextTick(()=>{
    if(win.$ && win.$('.xubox_msg.xubox_text').length && win.$('.xubox_msg.xubox_text').html()=="保存成功"){
      //开始填表2
      win.chooseBB('10101003','sb10101003Action.action?sign=initPage','100','101');
      nextTick(()=>{
        if(win.$ && win.$("#tab1 tr:eq(0) strong").length && win.$("#tab1 tr:eq(0) strong").html()=="一、申报抵扣的进项税额"){
          win.doTempSave();
          saveTable3(win);
          return true;
        }
      })
      return true;
    }
  },500)
}

const saveTable3=(win)=>{
  nextTick(()=>{
    if(win.$ && win.$('.xubox_msg.xubox_text').length && win.$('.xubox_msg.xubox_text').html()=="保存成功"){
      //开始填表3
      win.chooseBB('10101004','sb10101004Action.action?sign=initPage','100','101');
      nextTick(()=>{
        if(win.$ && win.$("#tab1 tr:eq(0) td:eq(0)").length && win.$("#tab1 tr:eq(0) td:eq(0)").html().trim()=="项目及栏次"){
          win.doTempSave();
          saveTable4(win);
          return true;
        }
      })
      return true;
    }
  },500)
}

const saveTable4=(win)=>{
  nextTick(()=>{
    if(win.$ && win.$('.xubox_msg.xubox_text').length && win.$('.xubox_msg.xubox_text').html()=="保存成功"){
      //开始填表4
      win.chooseBB('10101005','sb10101005Action.action?sign=initPage','100','101');
      nextTick(()=>{
        if(win.$ && win.$("#tab1 tr:eq(0) th").length && win.$("#tab1 tr:eq(0) th").html().trim()=="一、税额抵减情况"){
          win.doTempSave();
          saveTable5(win)
          return true;
        }
      })
      return true;
    }
  },500)
}

const saveTable5=(win)=>{
  nextTick(()=>{
    if(win.$('.xubox_msg.xubox_text').length && win.$('.xubox_msg.xubox_text').html()=="保存成功"){
      //开始填代扣代缴税收通用缴款书抵扣清单
      win.chooseBB('10101007','sb10101007Action.action?sign=initPage','100','101');
      nextTick(()=>{
        if(win.$ && win.$("#tab1 tr:eq(0) th:eq(0)").length && win.$("#tab1 tr:eq(0) th:eq(0)").html().trim()=="选择"){
          win.doTempSave();
          saveTable6(win);
          return true;
        }
      })
      return true;
    }
  },500)
}

const saveTable6=(win)=>{
  nextTick(()=>{
    if(win.$ && win.$('.xubox_msg.xubox_text').length && win.$('.xubox_msg.xubox_text').html()=="保存成功"){
      //开始填代扣代缴税收通用缴款书抵扣清单
      win.chooseBB('10101008','sb10101008Action.action?sign=initPage','100','101');
      nextTick(()=>{
        if(win.$ && win.$(".dbt").length && win.$(".dbt").html().trim()=="应税服务减除项目清单(差额征收资格纳税人适用)"){
          win.doTempSave();
          saveTable7(win);
          return true;
        }
      })
      return true;
    }
  },500)
}

const saveTable7=(win)=>{
  nextTick(()=>{
    if(win.$ && win.$('.xubox_msg.xubox_text').length && win.$('.xubox_msg.xubox_text').html()=="保存成功"){
      //开始填代扣代缴税收通用缴款书抵扣清单
      win.chooseBB('10101021','sb10101021Action.action?sign=initPage','100','101');
      nextTick(()=>{
        if(win.$ && win.$("#tab1 tr:eq(0) td:eq(0)").length && win.$("#tab1 tr:eq(0) td:eq(0)").html().trim()=="一、减税项目"){
          win.doTempSave();
          startCommit(win)
          return true;
        }
      })
      return true;
    }
  },500)
}


const startCommit=(win)=>{
  nextTick(()=>{
    if(win.$ && win.$('.xubox_msg.xubox_text').length && win.$('.xubox_msg.xubox_text').html()=="保存成功"){
      //开始填代扣代缴税收通用缴款书抵扣清单
      //win.goBack();
      //win.$("#goback_btn").click();
      //var $=win.$;
      //var str="indexMenuJump.action?sign=querysbzl&sb_type="+$("#sb_type").val()+"&zsxm_dm="+$("#zsxm_dm").val()+"&sssq_q="+$("#sssq_q").val()+"&sssq_z="+$("#sssq_z").val()+"&sb_zlbh="+$('#sb_zlid').val()+"&nsqx_dm="+$('#nsqx_dm').val()+"&sjly="+$('#sjly').val() +"&sb_bh="+$('#lsh').val()+"&ggyylybz="+ win.isNullReturnEmpty($('#ggyylybz').val());
      //console.log(str);
      //win.location.href=str;
      $("#contentiframe")[0].contentWindow.$(".tabs-close").click();
      nextTick(()=>{
        if($("#contentiframe").contents().find("#ente_home").length){
          $("#contentiframe")[0].contentWindow.entryClickSb();
          nextTick(()=>{
            let win=$("#contentiframe").contents().find("#mainIframe")[0].contentWindow;
            if(win.$ && win.$("#sbbtn").length){
              win.checkBbList();
              nextTick(()=>{
                if(win.$ && win.$(".xubox_yes.xubox_botton2").html()=="是"){
                  win.$(".xubox_yes.xubox_botton2").click();
                  nextTick(()=>{
                    if(win.$ && win.$(".xubox_yes.xubox_botton1").html()=="确定"){
                      win.$(".xubox_yes.xubox_botton1").click();
                      nextTick(()=>{
                        if(win.$ && win.$(".xubox_yes.xubox_botton1").length){
                          //if(win.$(".xubox_yes.xubox_botton1").html()==="附加税申报"){
                            //win.$(".xubox_yes.xubox_botton1").click();
                          //}else{
                          jumpInclude("https://etax.jiangsu.chinatax.gov.cn/portal/include_sb.do?app_bh=030121310&sssq_q="+getQueryString("sssq_q")+"&sssq_z="+getQueryString("sssq_z")+"&yrdbz=must","undefined","Y","undefined","城建税、教育费附加、地方教育附加税（费）申报表")
                          //}
                          setTimeout(()=>{
                            window.close();
                          },20000)
                          /*window.sessionStorage.clear();
		                      document.cookie = "GDS_PORTAL_NSRSBH='';expires=0;path=/";
                          window.location.href = "/portal/loginout.do";*/
                          return true;
                        }
                      },500)
                      return true;
                    }
                  })
                  return true;
                }
              })
              return true;
            }
          })
          return true;
        }
      });
      return true;
    }
  },1000);

}

const saveMainTable=(win)=>{
  nextTick(()=>{
    if(win.$ && win.$('.xubox_msg.xubox_text').length && win.$('.xubox_msg.xubox_text').html()=="保存成功"){
      win.chooseBB('10101001','sb10101001Action.action?sign=initPage','100','101');
      //开始填主表
      nextTick(()=>{
        if(win.$ && win.$("#tab1 tr:eq(0) b").html()=="增值税纳税申报表（一般纳税人适用）"){
          win.doTempSave();
          saveTable2(win);
          return true;
        }
      })
      return true;
    }
  },500)
}

const introMainTable=(win)=>{
  let str = win.$("#btsblb li:eq(1) em").attr('onclick');
  win.eval(str);
  nextTick(()=>{
    if(win.xxfpData){
      win.xxfpData();
      nextTick(()=>{
        if(win.$("#dialogjs").length){
          let dailogjsWin=win.$("#dialogjs")[0].contentWindow;
          if(dailogjsWin && dailogjsWin.msgImport){
            dailogjsWin.msgImport();
            nextTick(()=>{
              win.doTempSave();
              saveMainTable(win);
              return true
            },2000)
            return true;
          }
        }
      })
      return true;
    }
  },500)
}

const handleStep1=()=>{
  nextTick(()=>{
    if($("#contentiframe").contents().find("#ente_home").length){
      $("#contentiframe")[0].contentWindow.entryClickSb();
      nextTick(()=>{
        if($("#contentiframe").contents().find("#mainIframe").contents().find("#btn10406").length){
          let win=$("#contentiframe").contents().find("#mainIframe")[0].contentWindow;
          if(win.$("#btsblb li:eq(1) .state").html().trim()==="已填写"){
            introMainTable(win);
          }else{
            win.initData("initData");
            nextTick(()=>{
              if(win.$('.xubox_msg.xubox_text').length && win.$('.xubox_msg.xubox_text').html()=="初始化成功!"){
                introMainTable(win);
                return true;
              }
            })
          }
          return true;
        }
      })
      return true;
    }
  })
}



//有时候又是在iframe里的，和step2一样，就是多套了一层
const handleStep3=()=>{
  insertMoment();
  nextTick(()=>{
    if(!$("#contentiframe").length){
      return;
    }
    let win1=$("#contentiframe")[0].contentWindow;
    if(win1.$("#ente_home").length && window.moment){
      win1.checkMoreSb();
      nextTick(()=>{
        if(win1.$("#mainIframe").contents().find("#sbbtn_yjlsb").length){
          let win=win1.$("#mainIframe")[0].contentWindow;
          win.$("#btn_init").click();
          nextTick(()=>{
            if(win.$ && win.$(".xubox_yes.xubox_botton2").html()=="是"){
              win.$(".xubox_yes.xubox_botton2").click();
              nextTick(()=>{
                if(win.$('.xubox_msg.xubox_text').length && win.$('.xubox_msg.xubox_text').html()=="初始化成功!"){
                  win.$("#sbbtn_yjlsb").click();
                  nextTick(()=>{
                    if(win.$ && win.$(".xubox_yes.xubox_botton2").html()=="是"){
                      win.$(".xubox_yes.xubox_botton2").click();
                      sendSbList(currentZeroInfo);
                      nextTick(()=>{
                        window.sessionStorage.clear();
                        document.cookie = "GDS_PORTAL_NSRSBH='';expires=0;path=/";
                        window.location.href = "/portal/loginout.do";
                      },1000)
                      return true;
                    }else if(win.$ && win.$(".xubox_msg.xubox_text").html()==="您当期主税未申报，不符合零申报要求，请根据实际收入填写申报表"){
                      setTimeout(()=>{
                        window.location.reload();
                      },3000);
                    }
                  })
                  return true;
                }
              })
              return true;
            }
          })
          return true;
        }
      })
      return true;
    }
  })
}

const checkZeroReport = async ()=>{
  let timer = setInterval( async () => {
    if(currentZeroInfo){
      clearInterval(timer);
      timer = null;
      let isZero=window.sessionStorage.getItem("isZero"),isSmall=window.sessionStorage.getItem("isSmall");
      if(isZero!="true"){
        return;
      }

      if(isPage('index') && (typeof currentZeroInfo.cwbbInfo === 'object')) {
        let isCwbb = await isReprotCwbb();
        if (isCwbb) { // 财务报表
          handelCwbb1(currentZeroInfo);
          return;
        }
      }else if(isPage('step11')){
        handleStep11(currentZeroInfo);
        return;
      }

      // 印花税
      /*if(isPage('index')) {
        let isYHS = await isReport('印花税申报');
        if (isYHS) {
          $(isYHS).find('td:nth-child(7) div').click();
          return ;
        }
      }

      if (isPage('yhs')) {
        handelYHS(currentZeroInfo);
        return ;
      }*/

      // return true;

      if(isSmall!="true"){
        if(isPage('index')){
          (async ()=>{
            handleIndex();
          })();
        }else if(isPage('step1')){
          handleStep1();
        }else if(isPage('step3')){
          handleStep3();
        }else if(isPage('incomeStep')){
          incomeReport();
        }
      }else{
        if(isPage('index')){
          handleIndex();
        }else if(isPage('smallStep1')){
          handleSmallStep1();
        }else if(isPage('step3')){
          handleSmallStep3();
        }else if(isPage('incomeStep')){
          incomeReport();
        }
      }
      return true;
    }
  }, 200);

};



export {
  startZeroReport,
  checkZeroReport
};
